<template>
    <div class="departSelect">
        <van-search
            v-model="keyword"
            show-action            
            placeholder="请输入搜索关键词"
            @search="onSearch"
            >
            <template #action>
                <div class="searchBtns">
                    <van-button plain @click="onSearch" type="primary" size="small" style="margin-right: 10px;">查询</van-button>
                    <van-button plain @click="handleReset" size="small">重置</van-button>
                    
                </div>
            </template>
        </van-search>
        <div class="receivers">发送的对象:
            <div class="receiverList">{{ receiverNames }}</div>
        </div>
        <div class="selectPanel">            
            <van-tree-select                
                class="readonlyReceiverSelectTree"
                v-model:active-id="activeIds"
                v-model:main-active-index="activeIndex"
                @click-nav="handleClickNav"
                @click-item="handleClickLeader"
                :items="treeItems"
            >

            <template #content>
               
             <div class="treeSelectItemContent">
                <div class="selectToolbar">
                    <van-button size="mini" type="primary" plain @click="checkAll" style="margin-right: 10px;">全选</van-button>
                    <van-button size="mini" @click="toggleAll">取消全选</van-button>
                </div>
                
                <div class="selectItemBody">
                <van-checkbox-group v-model="activeIds" ref="checkboxGroupRef">
                    <van-cell-group inset>
                        <van-cell
                        v-for="(item, index) in activeItems"
                        clickable
                        :key="item.receiverId"
                        :title="item.receiverName"
                        @click="toggle(index,item)"                        
                        >
                        <template #right-icon>
                            <van-checkbox                            
                            :name="item"
                            :ref="el => checkboxRefs[index] = el"                            
                            />
                        </template>
                        </van-cell>
                    </van-cell-group>
                    </van-checkbox-group>        
                </div>
                </div>
            </template>

            </van-tree-select>
        </div>
    
    </div>
</template>



<script lang="ts" setup>
 

interface LeaderSelectProp{
    modelValue:Receiver[]
}

import { getInitReceiverList, getReceiverListByParent, searchReceiver } from '@/api/oaGroupApi';
import type { OaGroup, Receiver} from '@/types/workflow';
import type { TreeSelectItem, TreeSelectChild, CheckboxInstance } from 'vant';
import { onMounted, ref ,watch,defineProps, watchEffect, computed, nextTick} from 'vue';

const keyword = ref('')
const activeItems = ref<Receiver[]>([]) //右侧显示的receiver列表


const emiter = defineEmits(["update:modelValue"])
const {modelValue = null} = defineProps<LeaderSelectProp>();
const activeIds = ref([]);
const activeIndex = ref(0);
const treeItems = ref<TreeSelectItem[]>([]);
const checkboxRefs = ref<any>([]);
const toggle = (index:number,item:Receiver) => {
    //checkboxRefs.value[index].toggle();
    handleClickLeader(item,checkboxRefs.value[index].checked)    
};

const checkboxGroupRef = ref();

let initReceiverList:Receiver[] =[]; //初始化接收列表
const selectReceiverList = ref<Receiver[]>([]);

const isSearch = ref(false)

const receiverNames = computed(()=>{
    var names = ''
    var nameList:string[] = [];

    selectReceiverList.value.forEach((ele)=>{
        nameList.push(ele.receiverName)        
    });

    //nameList = removeDuplicates(nameList);
    nameList.forEach((ele)=>{
        names += ele + ";";
    })   

    return names;
});

//属性发生变化后重新计算
//注意这里监听的是getter函数，不能直接监听某个值，可以监听ref，reactive对象


watch(()=>modelValue,()=>{
    if(modelValue == null || modelValue.length == 0 ){        
        activeIds.value = [];                
    }
})
 
 
onMounted(()=>{
    initTopReceiverList();
})

//初始化顶层组列表
const initTopReceiverList = async ()=>{
    isSearch.value = false;
    const list = await  getInitReceiverList();    
    if(list.data){
        initReceiverList = list.data;         
    }else{
        initReceiverList = [];
    }

    //刷新treeitems
    const temp:TreeSelectItem[] = [];
    initReceiverList.forEach((ele)=>{
        temp.push({
            text:ele.receiverName
        })
    });
    treeItems.value = temp;

    nextTick(()=>{
        handleClickNav(0)
    })
}
 
const handleClickNav = async (index:number)  =>  {
    //如果是搜索，不处理
    if(isSearch.value )return;

    //
    var parentReceiver = initReceiverList[index];
    const list = await getReceiverListByParent(parentReceiver);

    //设置children
    if(list){
        var temp:TreeSelectChild[] = [];
        list.forEach((ele)=>{
            temp.push( {
                id:ele.receiverId,
                text:ele.receiverName
            });
        })
        treeItems.value[index].children = temp;
        parentReceiver.children = list;
        activeItems.value = list;
    }else{
        activeItems.value = [];
    }

    

}

const removeFromSelectList = (ele:Receiver)=>{
    var newArray:Receiver[] = [];
        for(var i=0;i<selectReceiverList.value.length;i++){
            if(selectReceiverList.value[i].receiverId != ele?.receiverId){
                newArray.push(selectReceiverList.value[i]);
            }
        }
        selectReceiverList.value = newArray;
}

const handleClickLeader = (item: Receiver,checked:boolean)=>{


    //获取点击的receiver
    var  theSelectReceiver = item;

    //新增或者删除
    if(checked && theSelectReceiver != null){
        selectReceiverList.value.push(theSelectReceiver); //新增
    }else{
        removeFromSelectList(theSelectReceiver)
    }

    emitUpdateModel();
}

const checkAll = () => {
    checkboxGroupRef.value.toggleAll(true);

    //将当前列表全部加入选择列表中
    activeItems.value.forEach((ele)=>{
        if(!isReceiverSelected(ele)){
            selectReceiverList.value.push(ele);
        }
    });
}



const toggleAll = () => {
    checkboxGroupRef.value.toggleAll(false)

    //将当前列表全部加入选择列表中
    activeItems.value.forEach((ele)=>{
        if(isReceiverSelected(ele)){
            removeFromSelectList(ele)
        }
    });
}

//是否已经选择了
const isReceiverSelected = (val:Receiver)=>{
    var selected = false;
    selectReceiverList.value.forEach((ele)=>{
        if(ele.receiverId == val.receiverId){
            selected = true;
        }
    })
    return selected;
}

const emitUpdateModel = ()=>{
    
    emiter('update:modelValue',selectReceiverList.value);
}

   
 
const onSearch = async ()=>{
    isSearch.value = true;
    if(keyword.value == '' ){
        initTopReceiverList();//
        return;
    }
    const list = await searchReceiver(keyword.value);

    treeItems.value = [{
        text:'搜索结果'
    }]
    if(list){
        activeItems.value = list;
    }else{
        activeItems.value = [];
    }
    
}

const handleReset = ()=>{
    selectReceiverList.value = [];
    keyword.value = ''
    activeIds.value = [];
    activeIndex.value = 0;
    initTopReceiverList();
}


    
    
</script>

<style lang="less" scoped>
.departSelect{
    width: 100%;
    .receivers{
        margin-bottom: 20px;
        display: flex;

        .receiverList{
            width: 100px;
            flex-grow: 1;
            padding-left: 10px;
            color:#1989fa;

            max-height: 50px;
            overflow-y: auto;
        }
    }
    .selectDepartTitle{
        text-align: center;
        padding-top: 20px;
        padding-bottom: 4px;
    }

    .selectPanel{
        
        border: 1px solid #dfdfdf;
        padding: 4px;

        .readonlyReceiverSelectTree{
            flex-grow: 1;
        }
    }

    .sendOptions{
        margin-top: 10px;
        margin-bottom: 20px;
    }

    .searchBtns{
        display: flex;
    }

    .treeSelectItemContent{
        display: flex;
        flex-direction: column;
        height: 100%;

        .selectToolbar{            
            z-index: 1;            
            background-color: #fff;            
            text-align: center;
            height: 40px;
            border-bottom: 1px solid #dfdfdf;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .selectItemBody{
            height: 100px;
            flex-grow: 1;
            overflow-y: auto;
        }
    }
}
</style>